
package com.hdoit.ares.quartz;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.util.StringUtils;

import com.hdoit.ares.logical.app.service.IAppRemindMessageService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.jpush.JpushClient;
import com.tennetcn.common.annotation.QuartzTaskConfig;
import com.tennetcn.common.aop.CommonApplicationContextUtil;
import com.tennetcn.common.logical.wechat.model.WechatOperateLog;
import com.tennetcn.common.logical.wechat.service.IWechatOperateLogService;
import com.tennetcn.common.selfcommon.enums.wechat.WechatOperateType;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.component.wechat.WechatManager;
import com.tennetcn.component.wechat.config.WechatConfiguration;

@QuartzTaskConfig(cronTrigger = "0 0 20 * * ?", jobTitle = "发送每日奖金消息")
public class QuartzSendMessageJob implements Job {
	/*"0 0 6,8,12,15,18,20,22 * * ?"*/
	
	//每日奖金通知
    public static final String awardPaySuccess;
    
    public static final String msgBlueColor="#173177";
    static{
    	WechatConfiguration config=WechatConfiguration.getInstance();
    	awardPaySuccess = config.getValue("wechat.template.awardPaySuccess");
    }
	
	//用于每日定时推送金豆和信息
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		//第一步找到所有的顾客
		ICustomerService customerService = CommonApplicationContextUtil.getCurrentContext().getBean(ICustomerService.class);
		IAppRemindMessageService appRemindMessageService = CommonApplicationContextUtil.getCurrentContext().getBean(IAppRemindMessageService.class);
		
		Date endDate = DateUtils.getCurrent();
		Date startDate = DateUtils.addDay(-1, endDate);
		
		List<Customer> customers = customerService.queryListForAward(startDate, endDate);

		for(Customer customer:customers){
			
			if(customer.getTotalGoldBean() != null && customer.getTotalGoldBean() > 0.00){
				double  goldBean = new BigDecimal(String.valueOf(customer.getTotalGoldBean())).setScale(0, BigDecimal.ROUND_DOWN).doubleValue();                                                           
				if(goldBean > 0){
					sendGoldBean("" + goldBean, endDate, customer);
					JpushClient.sendgoldBeanApp(goldBean, customer,appRemindMessageService);
				}
				
			}
			
           if(customer.getTotalMoney() != null && customer.getTotalMoney() > 0.00){
        	   double  money = new BigDecimal(String.valueOf(customer.getTotalMoney())).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
        	   if(money > 0.00){
        		   sendAwardMoney("" + money, endDate, customer);
        		   JpushClient.sendawardMoneyApp(money, customer,appRemindMessageService);
        	   }
			
           }
			
		}
	
	
	}
	

	
	public   String sendGoldBean(String goldBean,Date currentTime,Customer customer){
		
		
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		templateMessage.setToUser(customer.getOpenId());
		templateMessage.setTemplateId(awardPaySuccess);
		templateMessage.getData().add(new WxMpTemplateData("first","您今天的金豆收入为【"+goldBean+"】金豆",msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword1","金豆",msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword2",goldBean+"金豆",msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword3",DateUtils.convertDate2String(DateUtils.DATE_FORMAT,currentTime),msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("remark", "普天永利，让创业更简单",msgBlueColor));	
		long longTime = currentTime.getTime();
		String endTime = String.valueOf(longTime);
		
		String url = "www.putiyoli.net/ares/wechat/acc/myWealth/pushBillGoldBean?custId="+customer.getId()+"&endTime="+endTime;
		templateMessage.setUrl(url);
		return sendTemplateToWechat(templateMessage,customer);
		
	}
	
    public   String sendAwardMoney(String money,Date currentTime,Customer customer){
		
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		templateMessage.setToUser(customer.getOpenId());
		templateMessage.setTemplateId(awardPaySuccess);
		templateMessage.getData().add(new WxMpTemplateData("first","您今天的奖金收入为【"+money+"】元",msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword1","奖金",msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword2",money+"元",msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword3",DateUtils.convertDate2String(DateUtils.DATE_FORMAT,currentTime),msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("remark", "普天永利，让创业更简单", msgBlueColor));
		long longTime = currentTime.getTime();
		String endTime = String.valueOf(longTime);
		         
		String url = "www.putiyoli.net/ares/wechat/acc/myWealth/pushBillBonusList?custId="+customer.getId()+"&endTime="+endTime;
		templateMessage.setUrl(url);
																																													
		
		return sendTemplateToWechat(templateMessage,customer);
	 }

    private  String sendTemplateToWechat(WxMpTemplateMessage templateMessage,Customer customer){
		System.out.println("要发送的消息模板：");
		System.out.println(JsonUtils.toJson(templateMessage));
		WxMpService wxMpService = WechatManager.getInstance().getWxMpService();
		WxMpTemplateMsgService templateMsgService = wxMpService.getTemplateMsgService();
		//消息发送尝试
		//这种时候一般是我们请求微信服务器的时候没有成功，所以这里做三次尝试
		//当然还有就是到了微信，微信发送失败的情况，这个重试就在微信的回调事件里面了
		int count=0;
		String sendResultId=null;
		do{
			try {
				saveWechatOperateLog(customer,templateMessage,"sending");
				sendResultId=templateMsgService.sendTemplateMsg(templateMessage);
				if(!StringUtils.isEmpty(sendResultId)){
					count=3;
				}
				saveWechatOperateLog(customer,templateMessage,sendResultId);
			} catch (WxErrorException e) {
				e.printStackTrace();
			}
			count++;
		}while(count<3);
		
		return sendResultId;
	}
    
    private  boolean saveWechatOperateLog(Customer customer,WxMpTemplateMessage templateMessage,String resultType){
		WechatOperateLog wechatOperateLog=new WechatOperateLog();
		wechatOperateLog.setId(CommonUtils.getKeyId());
		wechatOperateLog.setOpenId(customer.getOpenId());
		wechatOperateLog.setOperateDate(DateUtils.getCurrent());
		wechatOperateLog.setUserId(customer.getId());
		wechatOperateLog.setUsername(customer.getUsername());
		wechatOperateLog.setOperateType(WechatOperateType.sendTemplateMessage);
		wechatOperateLog.setBusId(templateMessage.getTemplateId());
		wechatOperateLog.setOperateResult(resultType);
		wechatOperateLog.setContextData(JsonUtils.toJson(templateMessage));
		
		IWechatOperateLogService wechatOperateLogService= getWechatOperateLogService();
		if(wechatOperateLogService==null){
			return false;
		}
		return wechatOperateLogService.addModel(wechatOperateLog);
	}

	private  IWechatOperateLogService getWechatOperateLogService(){
		return CommonApplicationContextUtil.getCurrentContext().getBean(IWechatOperateLogService.class);
		
	}
	

}
